{
 "cells": [
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "### 11是否在 [5,7,11,22,27,33,39,52,58]",
   "id": "7781033caf18d92b"
  },
  {
   "cell_type": "code",
   "id": "initial_id",
   "metadata": {
    "collapsed": true,
    "ExecuteTime": {
     "end_time": "2025-03-01T10:11:09.758672Z",
     "start_time": "2025-03-01T10:11:09.728408Z"
    }
   },
   "source": [
    "#纯算\n",
    "arr_list=[5,7,11,22,27,33,39,52,58]\n",
    "num=11\n",
    "count=0\n",
    "left=0\n",
    "right=len(arr_list)-1\n",
    "while left<=right:\n",
    "    middle=(left+right)//2\n",
    "    count+=1\n",
    "    if num>arr_list[middle]:\n",
    "        left=middle+1\n",
    "    elif num<arr_list[middle]:\n",
    "        right=middle-1\n",
    "    else:\n",
    "        print(f'数字{num}已找到，索引值为{middle}')\n",
    "        break\n",
    "else:\n",
    "    print(f'数字{num}没有找到')\n",
    "print(f'一共用了{count}次查找')"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "数字11已找到，索引值为2\n",
      "一共用了3次查找\n"
     ]
    }
   ],
   "execution_count": 2
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-03-01T10:18:04.428399Z",
     "start_time": "2025-03-01T10:18:04.400758Z"
    }
   },
   "cell_type": "code",
   "source": [
    "#递归\n",
    "arr_list=[5,7,11,22,27,33,39,52,58]\n",
    "def binary_search(number,left,right):\n",
    "    if left<=right:\n",
    "        middle=(left+right)//2\n",
    "        if number <arr_list[middle]:\n",
    "            right=middle-1\n",
    "        elif number>arr_list[middle]:\n",
    "            left=middle+1\n",
    "        else:\n",
    "            return middle\n",
    "        return binary_search(number,left,right)\n",
    "    else:\n",
    "        return -1\n",
    "print(binary_search(11,0,len(arr_list)-1))#找到的话返回索引，未找到返回-1"
   ],
   "id": "d2f7c649fce4eb9e",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2\n"
     ]
    }
   ],
   "execution_count": 3
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
